/*******************************************************************************
 * Copyright 2010 MoBrite (A venture of Kinara Systems Private Limited)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.mobrite.domaindroid.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.mobrite.domaindroid.Constants;
import com.mobrite.domaindroid.Preferences;
import com.mobrite.domaindroid.R;
import com.mobrite.domaindroid.util.UiHelper;
import com.mobrite.domaindroid.util.Util;

public class SearchActivity extends Activity {
	
	EditText searchText;
//	EditText tldListText;
	AlertDialog mErrorDialog;
	
	CheckBox[] tldCheckBoxes = new CheckBox[12];

	// Menu Ids
	//static final int MENU_ID_ADD_TO_FAVOURITES 	= 1;
	static final int MENU_ID_DELETE 				= 2;
	static final int MENU_ID_LOOKUP_AGAIN		 	= 3;
	static final int MENU_ID_PREFS			 	= 4;
	static final int MENU_ID_ABOUT			 	= 5;

	UiHelper uiHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
				
		tldCheckBoxes[0] = (CheckBox) findViewById(R.id.CheckBox01);
		tldCheckBoxes[1] = (CheckBox) findViewById(R.id.CheckBox02);
		tldCheckBoxes[2] = (CheckBox) findViewById(R.id.CheckBox03);
		tldCheckBoxes[3] = (CheckBox) findViewById(R.id.CheckBox04);
		tldCheckBoxes[4] = (CheckBox) findViewById(R.id.CheckBox05);
		tldCheckBoxes[5] = (CheckBox) findViewById(R.id.CheckBox06);
		tldCheckBoxes[6] = (CheckBox) findViewById(R.id.CheckBox07);
		tldCheckBoxes[7] = (CheckBox) findViewById(R.id.CheckBox08);
		tldCheckBoxes[8] = (CheckBox) findViewById(R.id.CheckBox09);
		tldCheckBoxes[9] = (CheckBox) findViewById(R.id.CheckBox10);
		tldCheckBoxes[10] = (CheckBox) findViewById(R.id.CheckBox11);
		tldCheckBoxes[11] = (CheckBox) findViewById(R.id.CheckBox12);
		
		SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, 0);
		tldCheckBoxes[0].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_1, "com"));
		tldCheckBoxes[1].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_2, "net"));
		tldCheckBoxes[2].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_3, "org"));
		tldCheckBoxes[3].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_4, "in"));
		tldCheckBoxes[4].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_5, "mobi"));
		tldCheckBoxes[5].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_6, "eu"));
		tldCheckBoxes[6].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_7, "us"));
		tldCheckBoxes[7].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_8, "ac"));
		tldCheckBoxes[8].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_9, "info"));
		tldCheckBoxes[9].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_10, "cc"));
		tldCheckBoxes[10].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_11, "me"));
		tldCheckBoxes[11].setText(prefs.getString(Preferences.PREF_TLD_CHECKBOX_12, "tv"));
		
		searchText = (EditText) findViewById(R.id.search_src_text);
		searchText.setImeOptions(EditorInfo.IME_ACTION_DONE);
		searchText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
		uiHelper = new UiHelper(this);
		
//		tldListText = (EditText) findViewById(R.id.EditText02);		
//		tldListText.setImeOptions(EditorInfo.IME_ACTION_DONE);
//		tldListText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
		
		Button searchButton = (Button) findViewById(R.id.SearchButton);
		
		AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
		builder2.setCancelable(false)
		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.dismiss();
		           }
		       });
		mErrorDialog = builder2.create();

		searchButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				ValidationResult result = doClientValidation();
				if (!result.isSuccess()) {
					//mErrorPrompt.
					mErrorDialog.setTitle(result.getErrorString());
					mErrorDialog.setMessage(result.getErrorDescription());
					mErrorDialog.show();
					return;
				}
				else {
				
					Intent intent = new Intent(SearchActivity.this, ResultListActivity.class);
					intent.putExtra(Constants.EXTRA_DOMAIN, getDomainWithoutTldFromSearchStr());
					
					ArrayList<String> selectedTlds = new ArrayList<String>();
					//String tldListStr = tldListText.getText().toString().trim();
					
//					if (tldListStr.length()>0) {
//						String[] tldListArray = tldListStr.split(" ");
//						selectedTlds.addAll(Arrays.asList(tldListArray));
//					}

					String enteredTld = getTLDFromSearchStr();
					if (enteredTld.length()>0) {
						selectedTlds.add(enteredTld);
					}
					
					for (CheckBox cb : tldCheckBoxes) {
						if (cb.isChecked() && !cb.getText().toString().equals(enteredTld)) {
							selectedTlds.add(cb.getText().toString());
						}
					}
										
					intent.putExtra(Constants.EXTRA_TLDLIST, (String[]) selectedTlds.toArray(new String[0]));
					startActivity(intent);
				}
			}
		});
	}
	
	private String removeTrailingDot(String instr) {
		if (instr.endsWith(".")) {
			return instr.substring(0, instr.length()-2);
		}
		else {
			return instr;
		}
	}
	/**
	 * If the user entered TLD in the search box, return it
	 * @return
	 */
	private String getTLDFromSearchStr() {
		String searchStr = searchText.getText().toString().trim();
		if (searchStr.indexOf(".")<0) return "";
		
		String tld = "";
		//searchStr.substring(searchStr.indexOf(".")+1);
		
		try {
			String[] elems = searchStr.split("\\.");
			tld = elems[elems.length-1];
		} catch (Exception e) {
			tld = "";
			e.printStackTrace();
		}
		
		return tld;
	}
	
	private String getDomainWithoutTldFromSearchStr() {
		String searchStr = searchText.getText().toString().trim();
		if (searchStr.indexOf(".")<=0) {
			return searchStr;
		}
		return searchStr.substring(0, searchStr.indexOf("."));
	}
	
	private boolean isDomainStringValid() {
		return Pattern.matches("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$", searchText.getText().toString().trim());		
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	
        MenuItem prefsItem = menu.add(0, MENU_ID_PREFS, 0, getResources().getString(
                R.string.menu_prefs));
        prefsItem.setIcon(android.R.drawable.ic_menu_preferences);

        menu.add(0, MENU_ID_ABOUT, 0, getResources().getString(R.string.menu_about)).setIcon(android.R.drawable.ic_menu_help);

        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

    	switch (item.getItemId()) {
		case MENU_ID_PREFS:
			Intent intent = new Intent(this, PreferencesActivity.class);
			startActivity(intent);
			return true;

		case MENU_ID_ABOUT:
			uiHelper.showAboutDialog();
			return true;

		default:
			break;
		}
    	
    	return false;
    }

	private ValidationResult doClientValidation() {
		
		if (searchText.getText().length()==0) {
			return new ValidationResult(false, "Error", "Please Enter a Domain Name");
		}

		if (!isDomainStringValid()) {
			return new ValidationResult(false, "Error", "\""+searchText.getText().toString()+"\" is not a valid domain name");
		}
		
		if (getTLDFromSearchStr().equals("") && !isAtLeastOneCheckBoxChecked()) {
			return new ValidationResult(false, "Error", "Please select at least one TLD to lookup");
		}
		
//		if (tldListText.getText().length()>0) {
//			Pattern pattern = Pattern.compile("[a-zA-z\\s]+");
//			Matcher matcher = pattern.matcher(tldListText.getText());
//			if (!matcher.matches()) {
//				return new ValidationResult(false, "Error", "Invalid characters in extension list. Please enter a space-separated list of domain extensions");
//			}
//		}
		
		//if (tldListText.getText())
		return new ValidationResult(true);
	}
	
	private boolean isAtLeastOneCheckBoxChecked() {
		return tldCheckBoxes[0].isChecked() || tldCheckBoxes[1].isChecked() || tldCheckBoxes[2].isChecked() || tldCheckBoxes[3].isChecked();
	}
	
	private class ValidationResult {

		boolean success = false;
		String errorString;
		String errorDescription;
		
		public ValidationResult(boolean success, String errorString,
				String errorDescription) {
			super();
			this.success = success;
			this.errorString = errorString;
			this.errorDescription = errorDescription;
		}

		public ValidationResult(boolean success) {
			super();
			this.success = success;
		}

		public boolean isSuccess() {
			return success;
		}

		public void setSuccess(boolean success) {
			this.success = success;
		}

		public String getErrorString() {
			return errorString;
		}

		public void setErrorString(String errorString) {
			this.errorString = errorString;
		}

		public String getErrorDescription() {
			return errorDescription;
		}

		public void setErrorDescription(String errorDescription) {
			this.errorDescription = errorDescription;
		}
		
	}

//	class TldGridAdapter extends BaseAdapter {
//
//		CheckBox[] checkBoxes = new CheckBox[CommonData.TLD_LIST.length];
//		Context context;
//		
//		public TldGridAdapter(Context context) {
//			super();
//			this.context = context;
//			for (int i=0; i<checkBoxes.length; i++) {
//				checkBoxes[i] = new CheckBox(context);
//				checkBoxes[i].setText(CommonData.TLD_LIST[i]);
//			}
//		}
//
//		@Override
//		public int getCount() {
//			return CommonData.TLD_LIST.length;
//		}
//
//		@Override
//		public Object getItem(int position) {
//			return CommonData.TLD_LIST[position];
//		}
//
//		@Override
//		public long getItemId(int position) {
//			return 0;
//		}
//
//		@Override
//		public View getView(int position, View convertView, ViewGroup parent) {			
//			return checkBoxes[position];
//		}
//
//		public CheckBox[] getCheckBoxes() {
//			return checkBoxes;
//		}
//		
//	}
}
